#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:liang futing
#@Time :2019/4/9 9:59

import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.conf import settings

class RbacMiddleware(MiddlewareMixin):
    """
    user permission validate用户权限校验
    """
    def process_request(self,request):
        '''
        当用户请求进入时出发执行
        :param request:
        :return:
        1.获取当前用户请求的URL
        2.获取当前用户在session中保存的权限列表， ['/payment/list/', '/payment/add/',]
        3.权限信息匹配
        '''
        # http://127.0.0.1/customer/list/    path_info ->> /customer/list/
        #http://127.0.0.1/customer/list/?id=10&name='egon  path_info ->> /customer/list
        current_url=request.path_info
        for valid_url in settings.VALID_URL_LIST:
            if re.match(valid_url,current_url):
                #白名单中的URL无需权限验证即可访问
                return None
        #获取session中的权限列表
        permisson_dict=request.session.get(settings.PERMISSION_SESSION_KEY)
        if not permisson_dict:
            return HttpResponse('未获取到用户权限信息，请登录')

        url_record = [
            {'title': '首页', 'url': '#'}
        ]

        #此处的代码，用户登录后进行的判断 ：如果是logout 或index,不需要进行权限校验，就能访问的
        for url in settings.NO_PERMISSIONS_LIST:
            if re.match(url,current_url):
                request.current_selected_permission = 0
                request.breadcrumb = url_record
                return None


        flag=False
        #路径导航使用url_record

        for item in permisson_dict.values():
            reg='^%s$' % item['url']
            if re.match(reg,current_url):
                flag=True
                #如果 pid 存在就用pid,如果不存在就用id
                request.current_selected_permission=item['pid'] or item['id']
                if item['pid']:
                    #如果有pid,需要添加pid的title and url 到url_record
                    url_record.extend([{'title':item['p_title'],'url':item['p_url']},
                                      {'title':item['title'],'url':item['url'],'class':'active'}])
                else:
                    #如果没有pid,则添加自己的title and url
                    url_record.append({'title': item['title'], 'url': item['url'],'class':'active'})
                request.breadcrumb=url_record

                break
        # print(request.breadcrumb)
        # print(request.current_selected_permission)

        if not flag:
            return HttpResponse('无权访问')
        # default return None